<template>
  <div class="organization-selector">
    <div class="selector-container">
      <div class="selector-header">
        <h2>欢迎回来，{{ currentUser?.name }}</h2>
        <p>请选择要访问的组织</p>
      </div>

      <div class="organization-list">
        <el-row :gutter="20">
          <!-- 组织卡片 -->
          <el-col 
            v-for="org in organizations" 
            :key="org.id" 
            :xs="24" 
            :sm="12" 
            :md="8"
            class="org-col"
          >
            <el-card 
              class="org-card" 
              :class="{ 'active': selectedOrganization?.id === org.id }"
              @click="selectOrganization(org)"
            >
              <div class="org-card-content">
                <div class="org-avatar">
                  <el-avatar :size="48" :src="org.avatar">
                    {{ org.name.charAt(0) }}
                  </el-avatar>
                </div>
                <div class="org-info">
                  <h3 class="org-name">{{ org.name }}</h3>
                  <p class="org-code">{{ org.code }}</p>
                  <div class="org-role">
                    <el-tag type="primary" size="small">
                      {{ getUserRoleInOrganization(org.id) }}
                    </el-tag>
                  </div>
                  <div class="org-status">
                    <el-tag :type="org.status === 'active' ? 'success' : 'info'">
                      {{ org.status === 'active' ? '运营中' : '已停用' }}
                    </el-tag>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>

          <!-- 创建新组织卡片 -->
          <el-col :xs="24" :sm="12" :md="8" class="org-col">
            <el-card class="org-card create-card" @click="showCreateDialog = true">
              <div class="create-card-content">
                <div class="create-icon">
                  <el-icon><Plus /></el-icon>
                </div>
                <h3>创建新组织</h3>
                <p>添加新的公司或部门</p>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <div class="selector-footer">
        <el-button @click="goToDashboard" plain>
          暂不选择，直接进入系统
        </el-button>
      </div>
    </div>

    <!-- 创建组织对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      title="创建新组织"
      width="500px"
      @close="resetCreateForm"
    >
      <el-form 
        :model="createForm" 
        :rules="createRules" 
        ref="createFormRef"
        label-width="80px"
      >
        <el-form-item label="组织名称" prop="name">
          <el-input 
            v-model="createForm.name" 
            placeholder="请输入组织名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="组织编码" prop="code">
          <el-input 
            v-model="createForm.code" 
            placeholder="请输入组织编码"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="createForm.description" 
            placeholder="请输入组织描述"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="createOrganization"
          :loading="creatingOrganization"
        >
          创建
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
// @ts-nocheck
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useAppStore } from '@/stores/appStore'
import { organizationAPI } from '@/api/organization'

// 路由和状态管理
const router = useRouter()
const appStore = useAppStore()

// 响应式数据
const organizations = ref([])
const selectedOrganization = ref(null)
const showCreateDialog = ref(false)
const creatingOrganization = ref(false)
const currentUser = ref(null)
const userRoles = ref<Map<number, string>>(new Map())

// 表单引用
const createFormRef = ref()

// 创建组织表单数据
const createForm = reactive({
  name: '',
  code: '',
  description: ''
})

// 表单验证规则
const createRules = {
  name: [
    { required: true, message: '请输入组织名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入组织编码', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
}

// 方法
const loadOrganizations = async () => {
  try {
    // 获取当前用户信息
    currentUser.value = await appStore.getUserInfo()
    
    // 获取用户所属的组织列表
    const response: any = await organizationAPI.getUserOrganizations('current')
    if (response.success) {
      organizations.value = response.data
      
      // 获取用户在各组织中的角色
      await Promise.all(organizations.value.map(async (org: any) => {
        try {
          const roleResponse: any = await organizationAPI.getUserRoleInOrganization(
            appStore.user?.id || 0, 
            org.id
          )
          if (roleResponse.success) {
            userRoles.value.set(org.id, roleResponse.data.role || '成员')
          }
        } catch (error) {
          console.error(`获取组织${org.id}中的角色失败:`, error)
        }
      }))
      
      // 如果只有一个组织，直接选择并跳转
      if (organizations.value.length === 1) {
        selectOrganization(organizations.value[0])
      }
    } else {
      ElMessage.error('加载组织列表失败: ' + response.message)
    }
  } catch (error) {
    console.error('加载组织列表失败:', error)
    ElMessage.error('加载组织列表失败')
  }
}

const selectOrganization = (org) => {
  selectedOrganization.value = org
  // 保存选择的组织到应用状态
  appStore.setCurrentOrganization(org)
  localStorage.setItem('currentOrganization', JSON.stringify(org))
  ElMessage.success(`已选择组织: ${org.name}`)
  // 跳转到仪表板
  router.push('/dashboard')
}

const createOrganization = async () => {
  if (!createFormRef.value) return
  
  await createFormRef.value.validate(async (valid) => {
    if (valid) {
      creatingOrganization.value = true
      try {
        const response = await organizationAPI.createOrganization(createForm)
        if (response.success) {
          // 添加到组织列表
          const newOrg = {
            id: response.data.id,
            ...createForm,
            avatar: '',
            status: 'active'
          }
          
          organizations.value.push(newOrg)
          showCreateDialog.value = false
          
          ElMessage.success('组织创建成功')
          resetCreateForm()
        } else {
          ElMessage.error('创建组织失败: ' + response.message)
        }
      } catch (error) {
        console.error('创建组织失败:', error)
        ElMessage.error('创建组织失败: ' + error.message)
      } finally {
        creatingOrganization.value = false
      }
    }
  })
}

const resetCreateForm = () => {
  Object.assign(createForm, {
    name: '',
    code: '',
    description: ''
  })
}

const goToDashboard = () => {
  // 如果没有选择组织，使用第一个组织
  if (organizations.value.length > 0) {
    selectOrganization(organizations.value[0])
  } else {
    router.push('/dashboard')
  }
}

// 获取用户在组织中的角色
const getUserRoleInOrganization = (organizationId: number) => {
  return userRoles.value.get(organizationId) || '成员'
}

// 生命周期
onMounted(() => {
  loadOrganizations()
})
</script>

<style scoped>
.organization-selector {
  height: 100%;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4efe9 100%);
  padding: 20px;
  overflow: auto;
}

.selector-container {
  max-width: 1200px;
  margin: 0 auto;
}

.selector-header {
  text-align: center;
  margin-bottom: 30px;
  padding: 30px 0;
}

.selector-header h2 {
  font-size: 28px;
  font-weight: 600;
  margin: 0 0 10px 0;
  color: #1f2d3d;
}

.selector-header p {
  font-size: 16px;
  color: #666;
  margin: 0;
}

.organization-list {
  margin-bottom: 30px;
}

.org-col {
  margin-bottom: 20px;
}

.org-card {
  cursor: pointer;
  transition: all 0.3s ease;
  height: 100%;
  border: 2px solid transparent;
}

.org-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.org-card.active {
  border-color: #409eff;
  box-shadow: 0 0 0 2px #409eff;
}

.org-card-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  padding: 20px 0;
}

.org-avatar {
  margin-bottom: 15px;
}

.org-info {
  flex: 1;
}

.org-name {
  font-size: 18px;
  font-weight: 500;
  margin: 0 0 5px 0;
  color: #1f2d3d;
}

.org-code {
  font-size: 14px;
  color: #999;
  margin: 0 0 10px 0;
}

.org-role {
  margin-bottom: 8px;
}

.create-card {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: #f8f9fa;
  border-style: dashed;
  border-color: #dcdfe6;
}

.create-card:hover {
  border-color: #409eff;
  background: #f0f8ff;
}

.create-card-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.create-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: #ecf5ff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 15px;
}

.create-icon .el-icon {
  font-size: 24px;
  color: #409eff;
}

.create-card-content h3 {
  font-size: 18px;
  font-weight: 500;
  margin: 0 0 5px 0;
  color: #1f2d3d;
}

.create-card-content p {
  font-size: 14px;
  color: #999;
  margin: 0;
}

.selector-footer {
  text-align: center;
  padding: 20px 0;
}

@media (max-width: 768px) {
  .organization-selector {
    padding: 10px;
  }
  
  .selector-header {
    padding: 20px 0;
  }
  
  .selector-header h2 {
    font-size: 24px;
  }
  
  .org-col {
    margin-bottom: 15px;
  }
}
</style>